package com.zlzlib.okhttp.xml;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;

/**
 * xml解析工具
 *
 * @DateTime: 2023/8/24 16:42
 * @Author zlz
 * @Version 1.0
 */
public class XmlResultUtil {

    public static <T> T xmlToObj(String xml, Class<T> c) {
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        try {
            return xmlMapper.readValue(xml, c);
        } catch (JsonProcessingException e) {
            return null;
        }
    }

    public static String objToXml(Object o) {
        XmlMapper xmlMapper = new XmlMapper();
        try {
            return xmlMapper.writeValueAsString(o);
        } catch (JsonProcessingException e) {
            return "";
        }
    }

    public static String xmlGetLastString(String xml) {
        // 创建XmlMapper对象
        XmlMapper xmlMapper = new XmlMapper();
        // 解析XML数据
        JsonNode rootNode;
        try {
            rootNode = xmlMapper.readTree(xml);
        } catch (JsonProcessingException e) {
            return "";
        }
        // 获取内部最深层的数据
        JsonNode deepestNode = findLastNode(rootNode);
        if (deepestNode == null) {
            return "";
        }
        return deepestNode.asText();
    }

    /**
     * 递归查找内部最深层的节点
     *
     * @param node 主节点
     * @return 最后一个节点
     */
    private static JsonNode findLastNode(JsonNode node) {
        if (node.isObject() && node.size() > 0) {
            // 递归遍历子节点
            for (JsonNode childNode : node) {
                JsonNode result = findLastNode(childNode);
                if (result != null) {
                    return result;
                }
            }
        } else {
            // 叶子节点，返回该节点
            return node;
        }
        return null;
    }


}
